﻿using System;
using System.Collections.Generic;
using System.Text;

namespace DAO
{
    /// <summary>
    /// The <code>CodeFactory</code> class implements the common functions for all modules
    /// </summary>
    public static class CodeFactory
    {
        /// <summary>
        /// Calculates MD5 hashcode from a string. 
        /// </summary>
        /// <param name="str">The input string from which a MD5 hash should be 
        /// calculated</param>
        /// <returns>The result is the 32 character MD5 hashcode</returns>
        public static string CalcMD5String(string str)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider x =
                            new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(str);
            bs = x.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            return s.ToString();
        }

        public static string GetUniqueKey(int length)
        {
            string guidResult = string.Empty;

            while (guidResult.Length < length)
            {
                // Get the GUID.
                guidResult += Guid.NewGuid().ToString().GetHashCode().ToString("x");
            }

            // Make sure length is valid.
            if (length <= 0 || length > guidResult.Length)
                throw new ArgumentException("Length must be between 1 and " + guidResult.Length);

            // Return the first length bytes.
            return guidResult.Substring(0, length);
        }


        public static bool ContainsInvalidChars(string s)
        {
            string invalidChars = "!'\"$%~`";
            char c;
            bool hasSpecialChars = false;
            if(s !="")
            {
                for (int i = 0; i < s.Length && hasSpecialChars == false; i++)
                {
                    c = s[i];
                    if (invalidChars.IndexOf(c) != -1)
                        hasSpecialChars = true;
                }
            }
            return hasSpecialChars;
        }

        public static bool isNumeric(string s)
        {
            string invalidChars = "0123456789";
            char c;
            bool isNumber = true;
            if (s != "")
            {
                for (int i = 0; i < s.Length && isNumber == true; i++)
                {
                    c = s[i];
                    if (invalidChars.IndexOf(c) == -1)
                        isNumber = false;
                }
            }
            return isNumber;
        }
    }
}
